/**
 * Registration.java
 *
 * Created on Mar 7, 2010, 9:06:09 PM
 * 
 * @author Beatrice Bacelli
 * @author Luca Bedogni
 * @author Silvia Righini
 */

//NOTE
/*
 * Ho aggiunto il commento // PASSWORD davanti a tutte le parti 
 * che devono essere decommentate per riavere la nostra password
 */
package unibo.lsb.graphic;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.ListIterator;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import unibo.lsb.communication.RegistrationImpl;
import unibo.lsb.exception.TokioException;
import unibo.lsb.server.ConfigurationConstants;
import unibo.lsb.server.Game;

public class RegistrationWindow extends javax.swing.JFrame {

	private javax.swing.JButton btn_connect;
	private javax.swing.JButton btn_enterGame;
	private javax.swing.JButton btn_exitWindow;
	private javax.swing.JScrollPane scrollPane;
	// PASSWORD
	// private javax.swing.JLabel lbl_password;
	private javax.swing.JLabel lbl_server;
	private javax.swing.JLabel lbl_userName;
	private javax.swing.JTable tbl_gameList;
	private javax.swing.JComboBox cb_addresses;
	// PASSWORD
	// private javax.swing.JPasswordField txt_password;
	private javax.swing.JTextField txt_userName;

	RegistrationImpl ri = null;
	List<Game> lg = null;
	String serverAddress = "";
	NotificationDialog notificationDialog = null;
	boolean NotDialogToBeRisen = true;

	/** Creates new form Registration */
	public RegistrationWindow() {
		initComponents();

	}

	RegistrationWindow(JFrame jFrame) {
		initComponents();
	}

	private void initComponents() {

		setTitle("Register to game");
		setSize(new Dimension(532, 410));
		setLocationRelativeTo(null);

		cb_addresses = new javax.swing.JComboBox(
				ConfigurationConstants.POSSIBLE_SERVERS);
		lbl_server = new javax.swing.JLabel();
		btn_connect = new javax.swing.JButton();
		lbl_userName = new javax.swing.JLabel();
		txt_userName = new javax.swing.JTextField();
		// PASSWORD
		// txt_password = new javax.swing.JPasswordField();
		// lbl_password = new javax.swing.JLabel();
		btn_enterGame = new javax.swing.JButton();
		btn_exitWindow = new javax.swing.JButton();
		scrollPane = new javax.swing.JScrollPane();
		tbl_gameList = new javax.swing.JTable();

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowActivated(WindowEvent e) {
				btn_connect.requestFocusInWindow();
			}
		});

		setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				exitRegistration();
			}
		});

		cb_addresses.setEditable(true);
		cb_addresses.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				serverAddress = (String) cb_addresses.getSelectedItem();
			}
		});

		lbl_server.setText("Server");

		btn_connect.setText("Connect");
		btn_connect.addActionListener(new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btn_getGameListPressed(e);
			}
		});

		lbl_userName.setText("User Name");

		// PASSWORD
		// lbl_password.setText("Password");

		btn_enterGame.setText("Enter the game");
		btn_enterGame.addMouseListener(new java.awt.event.MouseAdapter() {
			@Override
			public void mousePressed(java.awt.event.MouseEvent evt) {
				btn_getEnterGamePressed(evt);
			}
		});

		btn_exitWindow.setText("Cancel");
		btn_exitWindow.addMouseListener(new java.awt.event.MouseAdapter() {
			@Override
			public void mousePressed(java.awt.event.MouseEvent evt) {
				btn_getExitWindowPressed(evt);
			}
		});

		tbl_gameList.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] { { null }, { null }, { null }, { null },
						{ null } }, new String[] { "" }) {

			private static final long serialVersionUID = -8670151489297784750L;

			boolean[] canEdit = new boolean[] { false };

			@Override
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		tbl_gameList
				.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
		tbl_gameList.setShowHorizontalLines(false);
		tbl_gameList.setShowVerticalLines(false);
		tbl_gameList.getTableHeader().setResizingAllowed(false);
		tbl_gameList.getTableHeader().setReorderingAllowed(false);

		scrollPane.setViewportView(tbl_gameList);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addContainerGap()
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addGroup(
																								layout
																										.createSequentialGroup()
																										.addComponent(
																												lbl_server)
																										.addPreferredGap(
																												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										.addComponent(
																												cb_addresses,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												213,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																										.addGap(
																												18,
																												18,
																												18)
																										.addComponent(
																												btn_connect))
																						.addGroup(
																								layout
																										.createParallelGroup(
																												javax.swing.GroupLayout.Alignment.TRAILING,
																												false)
																										.addComponent(
																												scrollPane,
																												javax.swing.GroupLayout.Alignment.LEADING)
																										.addGroup(
																												javax.swing.GroupLayout.Alignment.LEADING,
																												layout
																														.createSequentialGroup()
																														.addComponent(
																																lbl_userName)
																														.addPreferredGap(
																																javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																														.addComponent(
																																txt_userName,
																																javax.swing.GroupLayout.PREFERRED_SIZE,
																																150,
																																javax.swing.GroupLayout.PREFERRED_SIZE)
																														.addPreferredGap(
																																javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																										// PASSWORD
																										// .addComponent(
																										// lbl_password)
																										// .addGap(
																										// 18,
																										// 18,
																										// 18)
																										// .addComponent(
																										// txt_password,
																										// javax.swing.GroupLayout.PREFERRED_SIZE,
																										// 150,
																										// javax.swing.GroupLayout.PREFERRED_SIZE)
																										))))
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addGap(
																				150,
																				150,
																				150)
																		.addComponent(
																				btn_enterGame)
																		.addGap(
																				20,
																				20,
																				20)
																		.addComponent(
																				btn_exitWindow)))
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																lbl_server)
														.addComponent(
																cb_addresses,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																btn_connect))
										.addGap(18, 18, 18)
										.addComponent(
												scrollPane,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												228,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																lbl_userName)
														.addComponent(
																txt_userName,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
										// PASSWORD
										// .addComponent(
										// lbl_password)
										// .addComponent(
										// txt_password,
										// javax.swing.GroupLayout.PREFERRED_SIZE,
										// javax.swing.GroupLayout.DEFAULT_SIZE,
										// javax.swing.GroupLayout.PREFERRED_SIZE)
										)
										.addGap(25)
										.addGroup(
												layout
														.createParallelGroup()
														.addComponent(
																btn_enterGame,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE)
														.addComponent(
																btn_exitWindow,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE))
										.addContainerGap()));

	}

	private void btn_getGameListPressed(ActionEvent evt) {
		try {
			if (serverAddress.equals("")) {
				serverAddress = (String) cb_addresses.getSelectedItem();
			}
			ri = new RegistrationImpl(serverAddress);
			lg = ri.connectToServer();
			// Populate the list
			// txa_gameList.setText(lg);
			// now we have a list of games

			if (lg.isEmpty()) {
				GraphicUtils.displayDialog(this,
						"No game on server Try another one maybe..",
						"No game on server", JOptionPane.INFORMATION_MESSAGE,
						GraphicUtils.DO_NOTHING_ON_CLOSE);
			} else {
				// Display them
				ListIterator<Game> li = lg.listIterator();
				DefaultTableModel model = new DefaultTableModel() {
					/**
					 * 
					 */
					private static final long serialVersionUID = -7253893330725550600L;

					@Override
					public boolean isCellEditable(int row, int column) {
						return false;
					}
				};
				model.addColumn("");

				while (li.hasNext()) {
					Game g = li.next();
					model.insertRow(0, new Object[] { g.getName() + "."
							+ String.valueOf(g.getNumberOfPlayers())
							+ " players" });
				}
				tbl_gameList.setModel(model);
			}
		} catch (TokioException e) {
			e.DisplayErrorInDialog(this);
		}
	}

	private void btn_getEnterGamePressed(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_btn_getGameListPressed
		String username = txt_userName.getText();
		// PASSWORD
		// String password = txt_password.getPassword().toString();
		int g = tbl_gameList.getSelectedRow();

		if (ri == null) {
			GraphicUtils
					.displayDialog(
							this,
							"Can't enter game before connecting to server and choosing a game.",
							"Can't enter game", JOptionPane.ERROR_MESSAGE,
							GraphicUtils.DO_NOTHING_ON_CLOSE);
		} else if ((g == -1) || (lg.isEmpty())) {
			GraphicUtils.displayDialog(this, "No game has been selected.",
					"Can't enter game", JOptionPane.ERROR_MESSAGE,
					GraphicUtils.DO_NOTHING_ON_CLOSE);

		} else if ((username.trim().isEmpty() || username.equals(""))) {
			GraphicUtils.displayDialog(this, "Username is empty.",
					"Empty username", JOptionPane.ERROR_MESSAGE,
					GraphicUtils.DO_NOTHING_ON_CLOSE);
		}
		// PASSWORD
		// else if ((username.trim().isEmpty() || username.equals(""))
		// || (password.trim().isEmpty() || password.equals(""))) {
		// GraphicUtils.displayDialog(this, "Username or password is empty.",
		// "Empty username/password", JOptionPane.ERROR_MESSAGE);
		// }
		else if (username.trim().length() > ConfigurationConstGraphics.MAX_USERNAME_LENGTH) {
			GraphicUtils.displayDialog(this,
					"Username is too long. Use max 8 characters",
					"Username too long", JOptionPane.ERROR_MESSAGE,
					GraphicUtils.DO_NOTHING_ON_CLOSE);
		} else {
			try {
				// corresponding game in list
				g = tbl_gameList.getRowCount() - g - 1;
				Game game = lg.get(g);

				// PASSWORD
				if (ri.chooseGame(game.getName(), username, "")) {
					if (NotDialogToBeRisen) {
						notificationDialog = new NotificationDialog();
						notificationDialog.setVisible(true);
					}
					this.setVisible(false);
				}
			} catch (TokioException e) {
				e.DisplayErrorInDialog(this);
			}
		}
	}

	private void btn_getExitWindowPressed(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_btn_getGameListPressed
		exitRegistration();
	}

	private void exitRegistration() {
		MainWindowSingleton.getInstance().getMainWindow().setVisible(true);
		this.setVisible(false);
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new RegistrationWindow().setVisible(true);
			}
		});
	}

	public void setNotificationDialogNotVisible() {
		NotDialogToBeRisen = false;
		if (notificationDialog != null) {
			notificationDialog.setVisible(false);
		}
		this.setVisible(false);
	}
}